/**
 * Radio Story Cards - using RFID tags to track physical story cards in an agile/lean environment.
 *
 * See http://www.radiostorycards.com for more information.
 *
 *
 * Copyright (C) 2011, Ted M. Young
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
package com.radiostorycards.gui;

import org.jfugue.MidiRenderer;
import org.jfugue.Pattern;
import org.jfugue.Player;
import org.jfugue.parsers.MusicStringParser;

import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Sequence;
import javax.sound.midi.Sequencer;

/**
 * Plays a little 2- or 3-note tune to let the user know that something happened. Yes, it's probably overkill to use the
 * JFugue library to play a few notes, but it was nicer than just going "beep".
 *
 * @author Ted Young <tedyoung@gmail.com> @JitterTed
 */
public class SwipeTune {

  public static final Pattern SWIPED_TUNE = new Pattern("Gs A#s");
  public static final Pattern SUCCESS_TUNE = new Pattern("C6t Rt Eb6s");

  private Sequencer _sequencer;
  private Sequence _sequence;

  /**
   * Creates the pre-parsed tune so that it can be played with minimal delay from when the playSwiped() is called.
   */
  public SwipeTune() {
    _sequencer = new Player().getSequencer();
    MusicStringParser parser = new MusicStringParser();
    MidiRenderer renderer = new MidiRenderer(Sequence.PPQ, 128);
    parser.addParserListener(renderer);
    renderer.reset();
    parser.parse(SWIPED_TUNE);
    _sequence = renderer.getSequence();
    try {
      if (_sequencer.getSequence() == null) {
        _sequencer.setSequence(_sequence);
      }
    } catch (InvalidMidiDataException e) {
      e.printStackTrace();
    }
  }

  /**
   * Plays the "card was successfully swiped" tune.
   */
  public void playSwiped() {
    try {
      if (_sequencer.getSequence() == null) {
        _sequencer.setSequence(_sequence);
      }
    } catch (InvalidMidiDataException e) {
      e.printStackTrace();
    }
    try {
      if (!_sequencer.isOpen()) {
        _sequencer.open();
      }
      _sequencer.start();
    } catch (MidiUnavailableException e) {
      e.printStackTrace();
    }
  }

  /**
   * Plays the "success!" tune to, e.g., let the user know their input was accepted.
   */
  public void playSuccess() {
    new Player().play(SUCCESS_TUNE);
  }
}
